package com.hl.manage.controller;


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hl.manage.entity.Group;
import com.hl.manage.entity.Menu;
import com.hl.manage.service.IGroupService;
import com.hl.manage.service.IMenuService;
import com.hl.manage.utils.SendResult;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Helei
 * @since 2021-03-11
 */
@RestController
@RequestMapping("/manage/menu")
public class MenuController {
	
	
	private static final Logger log = LoggerFactory.getLogger(MenuController.class);
	
	@Autowired
	IMenuService imenu;
	
	@Autowired
	IGroupService iuser;
	/**
	 * 
	 * @param id
	 * @return 获取左侧菜单列表
	 */
	@RequestMapping("getmenu")
	public String getmenu(@Param("id") Integer id,@Param("type") Integer type, HttpServletRequest request) {
		HttpSession session = request.getSession();
		SendResult sResult = new SendResult();
		String groupIdString = session.getAttribute("loginGroup").toString();
		Group group = iuser.getById(groupIdString);
		String [] groupLiStrings = group.getMenuIdlist().split(",");
		//根据登录用户的权限获取菜单
		if(groupIdString.equals("1")) {
			List<Menu> limList = imenu.findByParentIdType(id, type);
			List<Object> list = new ArrayList<Object>();
			//循环顶级菜单
			for (Menu iterable_element : limList) {
				List<Menu> twList =  imenu.findByParentIdType(iterable_element.getId(), type);
				List<Object> twList2list = new ArrayList<Object>();
				JSONObject twObject = JSON.parseObject(iterable_element.toString());
				//循环二级菜单
				for (Menu twMenu : twList) {
					List<Menu> thList = imenu.findByParentIdType(twMenu.getId(), type);
					List<Object> thList2 = new ArrayList<Object>();
					JSONObject thObject = JSON.parseObject(twMenu.toString());
					//循环三级菜单
					for (Menu menu : thList) {
						thList2.add(menu);
					}
					thObject.put("children",thList2);
					twList2list.add(thObject);
				}
				twObject.put("children",twList2list);
				list.add(twObject);
			}
			sResult.setCode(200);
			sResult.setMsg("操作成功");
			sResult.setData(list.toString());
		}else {
			List<Menu> limList = imenu.findByParentIdType(id, type);
			List<Object> list = new ArrayList<Object>();
			//循环顶级菜单
			for (Menu iterable_element : limList) {
				if(!Arrays.asList(groupLiStrings).contains(iterable_element.getId().toString())) {
					continue;
				}
				List<Menu> twList =  imenu.findByParentIdType(iterable_element.getId(), type);
				List<Object> twList2list = new ArrayList<Object>();
				JSONObject twObject = JSON.parseObject(iterable_element.toString());
				//循环二级菜单
				for (Menu twMenu : twList) {
					List<Menu> thList = imenu.findByParentIdType(twMenu.getId(), type);
					List<Object> thList2 = new ArrayList<Object>();
					JSONObject thObject = JSON.parseObject(twMenu.toString());
					//循环三级菜单
					for (Menu menu : thList) {
						thList2.add(menu);
					}
					thObject.put("children",thList2);
					twList2list.add(thObject);
				}
				twObject.put("children",twList2list);
				list.add(twObject);
			}
			sResult.setCode(200);
			sResult.setMsg("操作成功");
			sResult.setData(list.toString());
		}
		return sResult.toString();
	}
	/**
	 * 根据id删除
	 * @param id
	 * @return
	 */
	@RequestMapping("/deletebyid")
	public String delById(@RequestParam(name = "id") String id){
		List<Menu> menu = imenu.findByParentId(Integer.parseInt(id));
		SendResult sResult = new SendResult();
		if (menu.isEmpty()) {
			imenu.removeById(id);
			sResult.setCode(200);
			sResult.setMsg("操作成功");
			sResult.setData(null);
			return sResult.toString();
		}else {
			sResult.setCode(400002);
			sResult.setMsg("请先删除子菜单");
			sResult.setData(null);
			return sResult.toString();
		}		
	}
	/**
	 * 根据id判断修改还是新增
	 * @param param {id:"",icon:"",ordern:"",parent:"",route:""}
	 * @return json
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/updatebyid")
	public String updatebuid(@RequestParam(name = "param") String param) throws UnsupportedEncodingException {	
		
		JSONObject jObject = JSONObject.parseObject(URLDecoder.decode(param.replaceAll("%25", ""), "UTF-8"));
		System.out.println(jObject.toString());
		
		Menu menu ;
		System.out.println(jObject.get("id").toString());
		if(jObject.get("id").toString().isEmpty()) {
			menu = new Menu();
		}else {
			menu = imenu.getById(jObject.get("id").toString());
			if(menu.getParentId()==0){
				System.out.println("之前的父级菜单ID"+menu.getParentId());
				Integer idInt = Integer.parseInt(jObject.get("parent").toString());
				List<Menu> menulList = imenu.findByParentId(Integer.parseInt(jObject.get("id").toString()));
				if (!menulList.isEmpty()&&menu.getParentId()!=idInt) {
					SendResult sResult = new SendResult();
					sResult.setCode(400004);
					sResult.setMsg("此菜单为父级菜单，请先将子菜单移除再进行移动操作");
					sResult.setData(menu.toString());
					return sResult.toString();
				}
			}
		}
		
		menu.setIcon(jObject.get("icon").toString());
		menu.setName(jObject.get("name").toString());
		menu.setType(Integer.parseInt(jObject.get("type").toString()));
		menu.setOrdern(Integer.parseInt(jObject.get("ordern").toString()));
		menu.setParentId(Integer.parseInt(jObject.get("parent").toString()));
		menu.setRoute(jObject.get("route").toString());
		imenu.saveOrUpdate(menu);
		
		SendResult sResult = new SendResult();
		sResult.setCode(200);
		sResult.setMsg("操作成功");
		sResult.setData(menu.toString());
		return sResult.toString();
	}
	/**
	 * 获取所有路由
	 * @param page
	 * @param limit
	 * @return json
	 */
	@RequestMapping("/page")
	public String getAllMenu(@RequestParam(name = "page")Integer page,@RequestParam(name = "limit") Integer limit) {

		List<String> list = new ArrayList<String>();
		List<Menu> limList = imenu.pageByParentId(0, page, limit);
		List<Menu> parent = imenu.findByParentId(0);
		Menu menu = new Menu();
		menu.setId(0);
		menu.setName("顶级菜单");
		parent.add(menu);
		IPage<Menu> iPage = new Page<Menu>(page, limit);
		log.info(limList.toString());
		for (Menu iterable_element : limList) {
			JSONObject jsonObj = JSON.parseObject(iterable_element.toString());
			jsonObj.put("children", imenu.findByParentId(iterable_element.getId()));
			jsonObj.put("total", imenu.page(iPage).getTotal());
			jsonObj.put("page", page);
			jsonObj.put("limit",limit);
			jsonObj.put("parent",parent);
			list.add(jsonObj.toJSONString());
		}
		SendResult sResult = new SendResult();
		sResult.setCode(200);
		sResult.setMsg("操作成功");
		sResult.setData(list.toString());
		return sResult.toString();
	}
}
